use sqlite_wasm_rs::{sqlite3, sqlite3_exec, SQLITE_OK};
use crate::db::db::{print_error, Db};

pub fn transaction<F: FnOnce(Db)->R, R>(db: Db, do_bussiness: F)-> R {
    begin(db.db());

    let r = do_bussiness(db.clone());

    commit(db.db());
    r
}

pub fn begin(db: *mut sqlite3) {
    unsafe {
        let ret = sqlite3_exec(db, c"BEGIN TRANSACTION".as_ptr().cast(),
                               None,
                               std::ptr::null_mut(),
                               std::ptr::null_mut(),);
        assert_eq!(ret, SQLITE_OK);
    }
}

pub fn commit(db: *mut sqlite3) {
    unsafe {
        let ret = sqlite3_exec(db, c"COMMIT".as_ptr().cast(),
                               None,
                               std::ptr::null_mut(),
                               std::ptr::null_mut(),);
        if ret != SQLITE_OK {
            print_error(db, ret, "commit failed");
        }
        assert_eq!(ret, SQLITE_OK);
    }
}